#!/bin/bash

# PK3 build script for Linux created by Chromium

# It takes one optional argument, an alternate destination path, meaning that
# calling for instance "./build.sh ~/doom" will build overload_code_*.pk3 directly
# into ~/doom instead. Fancy, eh?

# =============================================================================

if [ -z $1 ]; then
	dest="../trunk"
else
	if [ ! -d $1 ]; then
		echo "WARNING: You supplied $1 as destination path for me, but it doesn't exist or isn't a directory."
		echo "Will place built archive in trunk directory instead".
		dest="../trunk"
	elif [ ! -w $1 ]; then
		echo "WARNING: You supplied $1 as destination path for me, but it's not writable."
		echo "Will place built archive in trunk directory instead."
		dest="../trunk"
	else
		dest="$1"
	fi
fi

echo "Checking environment sanity... "
if [ -z $(which svn) -o -z $(which svnversion) ]; then
	echo "ERROR: You don't seem to have SVN installed! I need svn and svnversion commands available to build."
	exit 1
fi

if [ -z $(which zip) ]; then
	echo "ERROR: You don't seem to have zip installed! I need the zip command to be available to build."
	exit 1
fi

rev=$(svnversion)
fn="overload_code_r$rev.pk3"

if [ "$rev" == "exported" ]; then
	echo "ERROR: This is no SVN directory!"
	exit 2
fi

if [ ! -d "src" ]; then
	echo "ERROR: ./src either does not exist or is not a directory."
	exit 3
fi

if [ -d "../temp" ]; then
	# try move it out of the way
	if [ ! -d "../temp-1" ]; then
		mv ../temp ../temp-1
		echo "NOTICE: ../temp moved to ../temp-1. I need ../temp non-existant for building the package."
	else
		echo "ERROR: I need ../temp to be non-existant and would move it to ../temp-1 if the directory also didn't exist."
		echo "Please move ../temp out of the way for me so that I can build the package."
		exit 4
	fi
fi

if [ ! -w ".." ]; then
	echo "ERROR: I can't write into the parent directory! Please check the permissions and try again."
	exit 5
fi

echo "Environment OK. Going to build revision $rev."

echo -n "Exporting... "
svn export src ../temp >/dev/null
echo "done"

cd ../temp

echo -n "Creating archive $fn... "
zip -1 -r $fn * >/dev/null

if [ $? -ne 0 ]; then
	echo "ERROR: zip returned non-successfully."
	exit 1
fi

echo "done"

echo -n "Moving $fn... "
mv $fn $dest
if [ $? -ne 0 ]; then
	echo "Something went wrong with file moving. Stopping here.. please retrieve it from temp directory manually."
	echo "Also don't forget to delete temp directory afterwards."
	exit 1
fi
echo "done"

echo -n "Clearing temp directory... "
cd .. && rm -rf temp
echo "done"

echo "Finished!"
